package com.csii.activiti.server.core.config;

import cn.hutool.core.collection.CollUtil;
import com.csii.activiti.server.core.listener.AuditorGlobalListener;
import com.csii.activiti.server.core.listener.AutoApprovalListener;
import com.csii.activiti.server.core.listener.FlowEndListener;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ActivitiConfig {
    //todo 数据源连接池配置

    @Bean
    @ConditionalOnMissingBean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @ConditionalOnMissingBean
    public SpringProcessEngineConfiguration springProcessEngineConfiguration(PlatformTransactionManager platformTransactionManager ,DataSource dataSource, @Lazy AuditorGlobalListener auditorGlobalListener
            , @Lazy AutoApprovalListener autoApprovalListener, @Lazy FlowEndListener flowEndListener) {
        SpringProcessEngineConfiguration configuration = new SpringProcessEngineConfiguration();
        //配置全局事件监听
        Map<String, List<ActivitiEventListener>> typedListeners = new HashMap<>();
        typedListeners.put(ActivitiEventType.ACTIVITY_STARTED.name(),  CollUtil.newArrayList(auditorGlobalListener));
        typedListeners.put(ActivitiEventType.TASK_CREATED.name(), CollUtil.newArrayList(autoApprovalListener));
        typedListeners.put(ActivitiEventType.PROCESS_COMPLETED.name(), CollUtil.newArrayList(flowEndListener));

        configuration.setTypedEventListeners(typedListeners);

        configuration.setDataSource(dataSource);
        configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        configuration.setAsyncExecutorActivate(true);
        configuration.setTransactionManager(platformTransactionManager);
        return configuration;
    }

}
